import React, { Component } from 'react';
import CustomForm from '../../../components/CustomForm';
import { Input, Button, message, Select, Row, Col, Table, Tabs, Tooltip, Alert } from 'antd';
import services from '../../../services/api';
import Fields from './fields';
import { AUDIT, BANK_DATA_SOURCE } from '../../../utils/constant';
import Question from '../../../components/Question';

const Option = Select.Option;
const { TabPane } = Tabs;
const { Search } = Input;
const { TextArea } = Input;

class OuterListAdd extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mapping_relation: {},
      detail: null,
      activeRow: null,
      fileList: [],
      nameList: [],
      input_field_lists: [],
      mapInShows: [],
      input_field_shows: [],
      third_list_config_id: '',
      keywordAdd: '',
      keywordMap: '',
      columnsIn: [
        {
          title: '序号',
          dataIndex: 'param_id',
          key: 'param_id',
        },
        {
          title: '字段名',
          dataIndex: 'param_name',
          key: 'param_name',
        },
        {
          title: '字段code',
          dataIndex: 'param_code',
          key: 'param_code',
        },
        {
          title: '类型',
          dataIndex: 'data_type',
          key: 'data_type',
        },
        {
          title: '必填',
          dataIndex: 'required',
          key: 'required',
          render: (text, record) => {
            return record.required === 1 ? '是' : '否';
          },
        },
        {
          title: '长度',
          dataIndex: 'max_length',
          key: 'max_length',
        },
        {
          title: '描述',
          dataIndex: 'remark',
          key: 'remark',
        },
      ],
      columnsTestIn: [
        {
          title: '字段名',
          dataIndex: 'param_name',
          key: 'param_name',
        },
        {
          title: '类型',
          dataIndex: 'data_type',
          key: 'data_type',
        },
        {
          title: '长度',
          dataIndex: 'max_length',
          key: 'max_length',
        },
        {
          title: '必填',
          dataIndex: 'required',
          key: 'required',
          render: (text, record) => {
            return record.required === 1 ? '是' : '否';
          },
        },
        {
          title: '输入值',
          dataIndex: 'param_code',
          key: 'param_code',
          render: (text, record) => {
            return (
              <Input
                value={this.state.requestData[record.param_code]}
                onChange={(e) => {
                  const requestData = {
                    ...this.state.requestData,
                    [record.param_code]: e.target.value,
                  };
                  this.setState({
                    requestData,
                    requestJSON: JSON.stringify(requestData),
                  });
                }}
              />
            );
          },
        },
      ],
      columnsMap: [
        {
          title: '字段code',
          dataIndex: 'param_code',
          key: 'param_code',
          ellipsis: true,
        },
        {
          title: '字段名',
          dataIndex: 'param_name',
          key: 'param_name',
          ellipsis: true,
        },
        {
          title: '类型',
          dataIndex: 'data_type',
          key: 'data_type',
          ellipsis: true,
        },
        {
          title: '映射字段',
          dataIndex: 'mapping',
          key: 'mapping',
          width: '150px',
          ellipsis: true,
          render: (text, record) => {
            const show =
              this.state.mapping_relation &&
              this.state.mapping_relation[this.state.app_id] &&
              this.state.mapping_relation[this.state.app_id][this.state.event_id] &&
              this.state.mapping_relation[this.state.app_id][this.state.event_id][record.param_id]
                ? this.state.mapping_relation[this.state.app_id][this.state.event_id][record.param_id].field_code
                : '';
            return (
              <Tooltip title={show}>
                <div className='overflowtext' style={{ width: '100%' }}>
                  {show}
                </div>
              </Tooltip>
            );
          },
        },
      ],
      columnsOut: [
        {
          title: '序号',
          dataIndex: 'param_id',
          key: 'param_id',
        },
        {
          title: '字段名',
          dataIndex: 'param_name',
          key: 'param_name',
        },
        {
          title: '字段code',
          dataIndex: 'param_code',
          key: 'param_code',
        },
        {
          title: '类型',
          dataIndex: 'data_type',
          key: 'data_type',
        },
        {
          title: '长度',
          dataIndex: 'max_length',
          key: 'max_length',
        },
        {
          title: '描述',
          dataIndex: 'remark',
          key: 'remark',
        },
      ],
      columnsTestOut: [
        {
          title: '字段名',
          dataIndex: 'param_name',
          key: 'param_name',
        },
        {
          title: '字段code',
          dataIndex: 'param_code',
          key: 'param_code',
        },
        {
          title: '长度',
          dataIndex: 'max_length',
          key: 'max_length',
        },
        {
          title: '类型',
          dataIndex: 'data_type',
          key: 'data_type',
        },
      ],
      output_field_lists: [],
      output_field_shows: [],
      step: 1,
      showTest: false,
      app_id: '',
      event_id: '',
      requestData: {},
      requestJSON: '',
      responseJSON: '',
      url: '',
      asyncBtnVisible: false,
      asyncLoading: false,
    };
    this.actionType = 'add';
    this.form = null;
    this.api = 'outerList';
  }

  componentWillMount() {}

  componentDidMount() {
    this.actionType = this.props.actionType;
    if (this.props.actionType) {
      if (this.actionType === 'update' || this.actionType === 'detail') {
        this.third_list_id = this.props.id;
        this.getNameList(this.props.record.source);
      }
      if (this.actionType === 'map' || this.actionType === 'update' || this.actionType === 'detail') {
        this.nameListChange(this.props.record.third_list_config_id);
      }
      if (this.actionType === 'map') {
        this.setState({
          step: 2,
        });
      }
    }
  }

  goTestPage = () => {
    this.form.validateFields((err, values) => {
      if (values.url) {
        this.setState({
          showTest: true,
          url: values.url,
        });
      } else {
        message.error('URL必填');
      }
    });
  };

  testURL = () => {
    services[this.api]
      .testConnection({
        third_list_id: this.props.record.third_list_id,
        url: this.state.url,
        request_content: this.state.requestData,
      })
      .then((data) => {
        if (data.code === 0) {
          // message.success(data.msg || '请求成功');
          this.setState({
            responseJSON: JSON.stringify(data.data),
          });
        } else {
          message.error(data.msg);
        }
      });
  };

  updateInColumns(param) {
    const shows = this.state.input_field_lists.filter((item) => item.param_name.match(param ? param : ''));
    this.setState({
      input_field_shows: shows,
    });
  }

  updateOutColumns(param) {
    const shows = this.state.output_field_lists.filter((item) => item.param_name.match(param ? param : ''));
    this.setState({
      output_field_shows: shows,
    });
  }

  updateMapInColumns(param) {
    const mapIns = this.state.input_field_lists.filter((item) => item.param_name.match(param ? param : ''));
    this.setState({
      mapInShows: mapIns,
    });
  }

  getNameList(param) {
    services[this.api].getNameList({ source: param }).then((res) => {
      if (res.code === 0) {
        this.setState({
          nameList: res.data,
        });

        if (this.actionType === 'add') {
          this.form.setFieldsValue({
            third_list_config_id: '',
          });
        } else if (this.actionType === 'update' && res.data) {
          for (let i = 0; i < res.data.length; i++) {
            if (res.data[i].third_list_config_id === this.props.record.third_list_config_id) {
              this.form.setFieldsValue({
                remark: res.data[i].remark,
              });
            }
          }
        }
      } else {
        message.error(res.msg);
      }
    });
  }

  // 新建映射、更新映射
  handleSubmit = () => {
    this.form.validateFields((err, values) => {
      if (!err && this.state.input_field_lists) {
        // for (let i = 0; i < this.state.input_field_lists.length; i++) {
        //   if (!this.state.input_field_lists[i].field_id || !this.state.input_field_lists[i].field_code) {
        //     message.error(`请为输入参数'${this.state.input_field_lists[i].param_name}'配置映射字段`);
        //     return;
        //   }
        // }
        const batch_mapping_relation = [];
        Object.keys(this.state.mapping_relation).forEach((keyApp) => {
          Object.keys(this.state.mapping_relation[keyApp]).forEach((keyEvent) => {
            const map = {
              app_id: keyApp,
              event_id: keyEvent,
              mapping_relation: [],
            };
            Object.keys(this.state.mapping_relation[keyApp][keyEvent]).forEach((keyMap) => {
              if (this.state.mapping_relation[keyApp][keyEvent][keyMap]) {
                map.mapping_relation.push(this.state.mapping_relation[keyApp][keyEvent][keyMap]);
              }
            });
            if (this.actionType !== 'add') {
              batch_mapping_relation.push(map);
            } else if (map.mapping_relation.length > 0) {
              batch_mapping_relation.push(map);
            }
          });
        });
        const params = {
          // app_id: this.state.app_id,
          // event_id: this.state.event_id,
          batch_mapping_relation,
        };
        if (this.actionType === 'add') {
          params.third_list_config_id = values.third_list_config_id;
          services[this.api].add(params).then((data) => {
            if (data.code === 0) {
              message.success(data.msg);
              if (this.props.closeModal) {
                this.props.closeModal();
              }
            } else {
              message.error(data.msg);
            }
          });
        } else {
          params.third_list_id = this.props.record.third_list_id;
          services[this.api].updateMapping(params).then((data) => {
            if (data.code === 0) {
              message.success(data.msg);
              if (this.props.closeModal) {
                this.props.closeModal();
              }
            } else {
              message.error(data.msg);
            }
          });
        }
      }
    });
  };

  // 更新三方名单
  handleSubmitEdit = () => {
    this.form.validateFields((err, values) => {
      if (!err) {
        if (values.url) {
          services.outerList[this.actionType]({
            third_list_id: this.props.record.third_list_id,
            url: values.url,
          }).then((data) => {
            if (data.code === 0) {
              message.success(data.msg);
              if (this.props.closeModal) {
                this.props.closeModal();
              }
            } else {
              message.error(data.msg);
            }
          });
        } else {
          message.error('URL必填');
        }
      }
    });
  };

  handleConfirmBlur = (e) => {
    const { value } = e.target;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  };

  activeFirstRow = () => {
    this.setState({
      activeRow:
        this.state.input_field_lists && this.state.input_field_lists.length > 0
          ? this.state.input_field_lists[0]
          : null,
    });
  };

  nextStep = () => {
    this.form.validateFields((err, values) => {
      if (!err) {
        this.setState({
          step: 2,
        });
        this.activeFirstRow();
      }
    });
  };

  prevStep = () => {
    this.setState({
      step: 1,
    });
  };

  nameListChange = (e) => {
    this.setState({
      third_list_config_id: e,
    });
    services[this.api].getNameListDetail({ third_list_config_id: e }).then((res) => {
      if (res.code === 0) {
        this.form.setFieldsValue({
          remark: res.data.remark,
        });
        this.setState({
          input_field_lists: res.data.input_field_list,
          output_field_lists: res.data.output_field_list,
        });
        this.updateInColumns();
        this.updateOutColumns();
        this.updateMapInColumns();
        this.setState({
          keywordAdd: '',
          keywordMap: '',
        });
        this.activeFirstRow();
      } else {
        message.error(res.msg);
      }
    });
  };

  smartMap = () => {
    if (!this.state.app_id) {
      message.warn('请选择渠道');
      return;
    }
    if (!this.state.event_id) {
      message.warn('请选择事件');
      return;
    }

    services[this.api]
      .smartMap({
        third_list_config_id: this.state.third_list_config_id || (this.record ? this.record.third_list_config_id : ''),
        app_id: this.state.app_id,
        event_id: this.state.event_id,
      })
      .then((res) => {
        if (res.code === 0) {
          res.data.forEach((item) => {
            this.updateMap(item, this.state.app_id, this.state.event_id, true);
          });
          this.initTableSelected();
        } else {
          message.error(res.msg);
        }
      });
  };

  onSourceChange = (e) => {
    this.getNameList(e);
    // 如果选中的行内数据源，则展示出同步按钮
    if (e === BANK_DATA_SOURCE) {
      this.setState({
        asyncBtnVisible: true,
      });
    }
  };

  filterField = (e) => {
    this.updateInColumns(e);
    this.updateOutColumns(e);
  };

  filterFieldMap = (e) => {
    this.updateMapInColumns(e);
  };

  activeRowClass = (record) => {
    return record === this.state.activeRow ? 'active-row' : '';
  };

  onRow = (record) => {
    return {
      onClick: () => {
        if (this.state.audit_status === AUDIT._WAIT) {
          return;
        }
        this.setState({ activeRow: record });
        this.initTableSelected(record);
      },
    };
  };

  updateMap = (field, app_id, event_id, isInit) => {
    if (isInit) {
      let map = field;
      if (this.state.mapping_relation[app_id]) {
        if (this.state.mapping_relation[app_id][event_id]) {
          this.state.mapping_relation[app_id][event_id][field.param_id] = map;
        } else {
          this.state.mapping_relation[app_id][event_id] = { [field.param_id]: map };
        }
      } else {
        this.state.mapping_relation[app_id] = { [event_id]: { [field.param_id]: map } };
      }
      this.setState({
        mapping_relation: { ...this.state.mapping_relation },
      });
    } else if (this.state.activeRow) {
      let map = {};
      if (field && field.length > 0) {
        for (let i = 0; i < this.state.input_field_lists.length; i++) {
          if (this.state.activeRow.param_id === this.state.input_field_lists[i].param_id) {
            map = {
              param_id: this.state.input_field_lists[i].param_id,
              param_code: this.state.input_field_lists[i].param_code,
              field_id: field[0].field_id,
              field_code: field[0].field_code,
            };
            break;
          }
        }
      } else {
        map = undefined;
      }
      if (this.state.mapping_relation[app_id]) {
        if (this.state.mapping_relation[app_id][event_id]) {
          this.state.mapping_relation[app_id][event_id][this.state.activeRow.param_id] = map;
        } else {
          this.state.mapping_relation[app_id][event_id] = { [this.state.activeRow.param_id]: map };
        }
      } else {
        this.state.mapping_relation[app_id] = { [event_id]: { [this.state.activeRow.param_id]: map } };
      }

      this.setState({
        mapping_relation: { ...this.state.mapping_relation },
      });
    }
  };

  updateAppAndEvent = (app_id, event_id, skipRequest) => {
    this.setState({
      app_id,
      event_id,
    });
    if (this.actionType === 'map' && app_id && event_id && !skipRequest) {
      services[this.api]
        .getMapping({
          third_list_id: this.props.record.third_list_id,
          app_id,
          event_id,
        })
        .then((res) => {
          if (res.code === 0 && res.data && res.data.list) {
            res.data.list.forEach((item) => {
              this.updateMap(item, app_id, event_id, true);
            });
            this.initTableSelected();
            this.setState({
              audit_status: res.data.audit_status,
            });
          } else {
            message.error(res.msg);
          }
        });
    }
  };

  initTableSelected(record) {
    record = record || this.state.activeRow;
    if (
      record &&
      this.state.mapping_relation &&
      this.state.mapping_relation[this.state.app_id] &&
      this.state.mapping_relation[this.state.app_id][this.state.event_id] &&
      this.state.mapping_relation[this.state.app_id][this.state.event_id][record.param_id] &&
      this.state.mapping_relation[this.state.app_id][this.state.event_id][record.param_id].field_id
    ) {
      this.refs.fields.updateSelectedRowKeys(
        this.state.mapping_relation[this.state.app_id][this.state.event_id][record.param_id].field_id
      );
    } else {
      this.refs.fields.updateSelectedRowKeys();
    }
  }

  // 新增同步数据功能
  asyncData() {
    this.setState({ asyncLoading: true });
    const source = this.form.getFieldValue('source');
    services.outerList.syncBankDataSource().then((res) => {
      if (res.code === 0) {
        this.setState({ asyncLoading: false });
        this.getNameList(source);
      } else {
        message.error(res.msg);
        this.setState({ asyncLoading: false });
      }
    });
  }

  render() {
    const formItems = [
      {
        label: {
          label: '名单',
          className: 'tantuer-form-item2',
        },
        name: 'source',
        options: {
          initialValue: (this.props.record || {}).source,
          rules: [{ required: true, message: '请填写名单名称' }],
        },
        component: (
          <Select
            style={this.state.asyncBtnVisible ? { width: '300px' } : null}
            placeholder='请选择'
            disabled={this.actionType !== 'add'}
            onChange={(e) => this.onSourceChange(e)}
          >
            {(this.props.third_namelist_source || []).map((item, index) => {
              return (
                <Option value={item.key} key={item.key}>
                  {item.value}
                </Option>
              );
            })}
          </Select>
        ),
        after: this.state.asyncBtnVisible ? (
          <Button onClick={this.asyncData.bind(this)} loading={this.state.asyncLoading}>
            同步
          </Button>
        ) : null,
      },
      {
        label: {
          label: '',
          className: 'tantuer-form-item2 tantuer-form-item-nowrap',
        },
        name: 'third_list_config_id',
        options: {
          initialValue: (this.props.record || {}).third_list_config_id,
          rules: [{ required: true, message: '请选择' }],
        },
        component: (
          <Select placeholder='请选择' disabled={this.actionType !== 'add'} onChange={this.nameListChange}>
            {this.state.nameList.map((item) => {
              return (
                <Option
                  value={item.third_list_config_id}
                  key={item.third_list_config_id}
                  disabled={item.mapping_status === 1}
                >
                  {item.name}
                </Option>
              );
            })}
          </Select>
        ),
      },
      {
        label: {
          label: '描述',
          className: 'tantuer-form-item2',
        },
        name: 'remark',
        options: {
          initialValue: (this.props.record || {}).remark,
          rules: [
            { max: 256, message: '最长256个字符' }
          ]
        },
        component: <Input placeholder='' disabled />,
      },
      this.actionType !== 'add'
        ? {
            label: {
              label: 'URL',
            },
            name: 'url',
            span: 8,
            options: {
              initialValue: (this.props.record || {}).url,
              rules: [
                { required: true, message: '请填写' },
                // {
                //   pattern: /^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(?::\d{1,5})?/i,
                //   message: '请输入正确的URL',
                // },
              ],
            },
            component: <Input placeholder='请填写' disabled={this.actionType === 'detail'} />,
            after: (
              <Button
                type='primary'
                className='marl10'
                onClick={this.goTestPage}
                disabled={this.actionType === 'detail'}
              >
                测试连接
              </Button>
            ),
          }
        : false,
    ].filter(Boolean);
    return (
      <div>
        <div style={{ display: this.state.step === 1 ? 'block' : 'none' }}>
          {!this.state.showTest ? (
            <div>
              <Row>
                <Col>
                  <CustomForm
                    {...this.props}
                    closeModal={this.props.closeModal}
                    createForm={(ref) => (this.form = ref)}
                    formItems={formItems}
                    onHandleSubmit={this.handleSubmit}
                    hideSubmit={true}
                    colNum={2}
                  />
                </Col>
              </Row>
              <Row>
                <Col>
                  <Search
                    placeholder='请输入字段名'
                    onSearch={this.filterField}
                    allowClear
                    onChange={(e) => {
                      this.setState({
                        keywordAdd: e.target.value,
                      });
                    }}
                    value={this.state.keywordAdd}
                    style={{ position: 'absolute', width: '20%', right: 0, zIndex: 1 }}
                  />
                  <Tabs defaultActiveKey='1'>
                    <TabPane tab='输入参数' key='1'>
                      <Table
                        columns={this.state.columnsIn}
                        dataSource={this.state.input_field_shows}
                        pagination={false}
                        rowKey='param_id'
                      />
                    </TabPane>
                    <TabPane tab='输出参数' key='2'>
                      <Table
                        columns={this.state.columnsOut}
                        dataSource={this.state.output_field_shows}
                        pagination={false}
                        rowKey='param_id'
                      />
                    </TabPane>
                  </Tabs>
                </Col>
                <div className='form-btn' style={{ marginTop: '30px' }}>
                  {this.actionType === 'add' ? (
                    <Button type='primary' onClick={this.nextStep} autoFocus={true}>
                      下一步
                    </Button>
                  ) : (
                    ''
                  )}
                  {this.actionType === 'update' ? (
                    <>
                      <Button type='primary' onClick={this.handleSubmitEdit}>
                        确定
                      </Button>
                      <Button onClick={() => this.props.closeModal(true)}>取消</Button>
                    </>
                  ) : (
                    ''
                  )}
                </div>
              </Row>
            </div>
          ) : (
            <div>
              <Row gutter={20}>
                <Col span={14}>
                  <Search
                    placeholder='请输入字段名'
                    onSearch={this.filterField}
                    value={this.state.keywordAdd}
                    onChange={(e) => {
                      this.setState({
                        keywordAdd: e.target.value,
                      });
                    }}
                    allowClear
                    style={{ position: 'absolute', width: '30%', right: 0, zIndex: 1 }}
                  />
                  <Tabs defaultActiveKey='1'>
                    <TabPane tab='输入参数' key='1'>
                      <Table
                        columns={this.state.columnsTestIn}
                        dataSource={this.state.input_field_shows}
                        pagination={false}
                        rowKey='param_id'
                      />
                    </TabPane>
                    <TabPane tab='输出参数' key='2'>
                      <Table
                        columns={this.state.columnsTestOut}
                        dataSource={this.state.output_field_shows}
                        pagination={false}
                        rowKey='param_id'
                      />
                    </TabPane>
                  </Tabs>
                </Col>
                <Col span={10}>
                  <p>请求内容</p>
                  <TextArea rows={14} value={this.state.requestJSON} />
                  <p>返回内容</p>
                  <TextArea rows={10} disabled value={this.state.responseJSON} style={{ color: '#888' }} />
                </Col>
              </Row>
              <div className='form-btn'>
                <Button type='primary' onClick={this.testURL}>
                  测试
                </Button>
                <Button
                  className='marl10'
                  onClick={() => {
                    this.setState({
                      showTest: false,
                    });
                  }}
                >
                  取消
                </Button>
              </div>
            </div>
          )}
        </div>
        <div className='tantuer' style={{ display: this.state.step === 2 ? 'block' : 'none' }}>
          <Row style={{ marginBottom: '15px' }} gutter={20}>
            <Col span={18}>
              <p>在使用名单的输出字段前，请先将名单的输入字段进行映射。</p>
            </Col>
            <Col span={6} style={{ textAlign: 'right' }}>
              <Button type='primary' onClick={this.smartMap} disabled={this.state.audit_status === AUDIT._WAIT}>
                智能映射
              </Button>
              <Question title='智能映射自动将名单、风控事件里名称相同的字段进行映射；如已在其他事件执行了映射操作，事件间相同的字段映射关系可通过智能映射来复制' />
            </Col>
          </Row>
          <Row gutter={20}>
            {this.state.audit_status === AUDIT._WAIT && (
              <Col span={24} style={{ marginBottom: '20px' }}>
                <Alert message='当前映射关系处于待审核状态，暂时无法修改！' type='warning' />
              </Col>
            )}
            <Col span={10}>
              <div className='map-origin'>
                <span>名单输入字段</span>
                <Search placeholder='请输入字段名' onSearch={this.filterFieldMap} allowClear />
                <Table
                  rowClassName={this.activeRowClass}
                  columns={this.state.columnsMap}
                  dataSource={this.state.mapInShows}
                  pagination={false}
                  onRow={this.onRow}
                  rowKey='param_id'
                  className='fixed'
                />
              </div>
            </Col>
            <Col span={14}>
              <div className='map-origin'>
                <span>风控事件字段</span>
                <Fields
                  ref='fields'
                  updateMap={this.updateMap}
                  updateAppAndEvent={this.updateAppAndEvent}
                  activeRow={this.state.activeRow}
                  mapping_relation={this.state.mapping_relation}
                  disabled={this.state.audit_status === AUDIT._WAIT}
                />
              </div>
            </Col>
            <Col span={24} className='form-btn' style={{ marginTop: '30px' }}>
              {this.actionType === 'add' ? (
                <Button type='primary' onClick={this.prevStep}>
                  上一步
                </Button>
              ) : (
                ''
              )}
              <Button
                type='primary'
                onClick={this.handleSubmit}
                className='marl10'
                disabled={this.state.audit_status === AUDIT._WAIT}
              >
                确定
              </Button>
              <Button
                onClick={() => this.props.closeModal(true)}
                className='marl10'
                disabled={this.state.audit_status === AUDIT._WAIT}
              >
                取消
              </Button>
            </Col>
          </Row>
        </div>
      </div>
    );
  }
}

export default OuterListAdd;
